<?php
/**
 * Created by jinqiang on 2024/4/29 16:07.
 * Copyright (c) 2024, Your Company. All rights reserved.
 */


namespace App\Http\Services\System;


use App\Http\Models\Mysql\NnyyMenuTable;
use App\Http\Models\Mysql\NnyyRolePermission;
use App\Http\Models\Mysql\NnyyRoleTable;

class RoleService
{
    public function search($param)
    {
        $conn = new NnyyRoleTable();
        if($param['label'] != ""){
            $conn = $conn->where('label', "like", "%".$param['label']."%");
        }
        if($param['role'] ?? []){
            $roles = implode("%", $param['role']);
            $rolePermissionRes = (new NnyyRolePermission())->where('menu_ids', 'like', "%".$roles."%")->get(['role_id'])->toArray();
            if(!empty($rolePermissionRes)){
                $conn = $conn->whereIn('id', array_column($rolePermissionRes, 'role_id'));
            }else{
                return ['data' => [], 'total' => 0];
            }
        }
        $res = $conn->paginate((Int)$param['limit'])->toArray();
        return ['data' => $res['data'], 'total' => $res['total']];
    }

    public function updateData($id, $param)
    {
        $data = [
            'type' => $param['type'],
            'label' => $param['label']
        ];
        $exist = (new NnyyRoleTable())->where('id', "<>", $id)->where(function ($query) use($param) {
                $query->where('type', $param['type'])
                    ->orWhere('label', $param['label']);
            })->exists();
        if(!empty($exist)){
            return ['code' => -1, 'msg' => '该角色类型或名称已存在'];
        }
        return (new NnyyRoleTable())->updateData($id, $data);
    }

    public function addData($param)
    {
        $data = [
            'type' => $param['type'],
            'label' => $param['label']
        ];
        $exist = (new NnyyRoleTable())->where('type', $param['type'])->orWhere('label', $param['label'])->exists();
        if(!empty($exist)){
            return ['code' => -1, 'msg' => '该角色类型或名称已存在'];
        }
        return (new NnyyRoleTable())->createData($data);
    }

    public function getPermission($roleId)
    {
        $rolePermissionObj = (new NnyyRolePermission())->where("role_id", $roleId)->first();
        if(empty($rolePermissionObj)){
            return [];
        }
        $rolePermissionData = $rolePermissionObj->toArray();
        $rolePermissionData['menu_ids'] = json_decode($rolePermissionData['menu_ids'], true);
        if(isset($rolePermissionData['node_actions']) && !empty($rolePermissionData['node_actions'])){
            $rolePermissionData['node_actions'] = json_decode($rolePermissionData['node_actions'], true);
        }
        return $rolePermissionData;
    }

    public function savePermission($roleId, $param)
    {
        //判断操作权限的路由是否存在 且 是叶子节点
        $nodeActions = json_decode($param['node_actions'], true);
        $routes = array_keys($nodeActions);
        $routeList = (new NnyyMenuTable())->whereIn('id', $routes)->get(['id'])->toArray();
        $routeListIds = array_column($routeList, 'id');
        foreach ($nodeActions as $id => $actions){
            if(!in_array($id, $routeListIds)){
                unset($nodeActions[$id]);
            }
            if(empty($actions)){
                unset($nodeActions[$id]);
            }
        }
        $parentRouteList = (new NnyyMenuTable())->whereIn('p_id', $routes)->get(['p_id'])->toArray();
        foreach ($parentRouteList as $item){
            if(isset($nodeActions[$item['p_id']])){
                unset($nodeActions[$item['p_id']]);
            }
        }
        $data = [
            'role_id' => $roleId,
            'menu_ids' => $param['menu_ids'],
            'node_actions' => json_encode($nodeActions)
        ];
        $permissionObj = (new NnyyRolePermission())->where('role_id', $roleId)->first();
        if(!empty($permissionObj)){
            $id = $permissionObj->id;
            return (new NnyyRolePermission())->updateData($id, $data);
        }
        return (new NnyyRolePermission())->createData($data);
    }
}
